import React, { useState } from 'react';
import {
  Box,
  Typography,
  Grid,
  Card,
  CardMedia,
  CardActions,
  IconButton,
  Button,
  Checkbox,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import {
  Delete,
  Add,
  SelectAll,
  Clear,
} from '@mui/icons-material';
import { MediaUploader } from './MediaUploader';

interface ImageManagerProps {
  contentId: number;
  currentImages: { id: number; imageUrl: string; createdAt: string; }[];
  onUpdate: (deleteIds: string[], newImages: File[]) => Promise<void>;
  loading?: boolean;
}

export const ImageManager: React.FC<ImageManagerProps> = ({
  contentId,
  currentImages,
  onUpdate,
  loading = false,
}) => {
  const [selectedImages, setSelectedImages] = useState<Set<number>>(new Set());
  const [newImages, setNewImages] = useState<File[]>([]);
  const [newImagePreviews, setNewImagePreviews] = useState<string[]>([]);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);

  const handleImageSelect = (imageId: number) => {
    const newSelected = new Set(selectedImages);
    if (newSelected.has(imageId)) {
      newSelected.delete(imageId);
    } else {
      newSelected.add(imageId);
    }
    setSelectedImages(newSelected);
  };

  const handleSelectAll = () => {
    if (selectedImages.size === currentImages.length) {
      setSelectedImages(new Set());
    } else {
      setSelectedImages(new Set(currentImages.map(img => img.id)));
    }
  };

  const handleAddImage = async (file: File) => {
    // 创建预览
    const reader = new FileReader();
    reader.onload = (e) => {
      setNewImagePreviews(prev => [...prev, e.target?.result as string]);
    };
    reader.readAsDataURL(file);
    
    setNewImages(prev => [...prev, file]);
  };

  const handleRemoveNewImage = (index: number) => {
    setNewImages(prev => prev.filter((_, i) => i !== index));
    setNewImagePreviews(prev => prev.filter((_, i) => i !== index));
  };

  const handleDeleteSelected = () => {
    if (selectedImages.size > 0) {
      setDeleteConfirmOpen(true);
    }
  };

  const confirmDelete = async () => {
    try {
      // 将选中的图片ID转换为字符串数组
      const deleteIds = Array.from(selectedImages).map(id => id.toString());

      await onUpdate(deleteIds, newImages);
      
      // 重置状态
      setSelectedImages(new Set());
      setNewImages([]);
      setNewImagePreviews([]);
      setDeleteConfirmOpen(false);
    } catch (err) {
      console.error('删除图片失败:', err);
    }
  };

  const handleSaveChanges = async () => {
    if (newImages.length > 0 || selectedImages.size > 0) {
      try {
        const deleteIds = Array.from(selectedImages).map(id => id.toString());

        await onUpdate(deleteIds, newImages);
        
        // 重置状态
        setSelectedImages(new Set());
        setNewImages([]);
        setNewImagePreviews([]);
      } catch (err) {
        console.error('保存更改失败:', err);
      }
    }
  };

  const hasChanges = newImages.length > 0 || selectedImages.size > 0;

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        图片管理
      </Typography>

      {/* 当前图片 */}
      {currentImages.length > 0 && (
        <Box sx={{ mb: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
            <Typography variant="subtitle1">
              当前图片 ({currentImages.length}张)
            </Typography>
            <Box>
              <Button
                size="small"
                startIcon={selectedImages.size === currentImages.length ? <Clear /> : <SelectAll />}
                onClick={handleSelectAll}
              >
                {selectedImages.size === currentImages.length ? '取消全选' : '全选'}
              </Button>
              {selectedImages.size > 0 && (
                <Button
                  size="small"
                  color="error"
                  startIcon={<Delete />}
                  onClick={handleDeleteSelected}
                  sx={{ ml: 1 }}
                >
                  删除选中 ({selectedImages.size})
                </Button>
              )}
            </Box>
          </Box>

                     <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
            {currentImages.map((image, index) => (
              <Box key={image.id} sx={{ width: { xs: 'calc(50% - 8px)', sm: 'calc(33.33% - 11px)', md: 'calc(25% - 12px)' } }}>
                <Card
                  sx={{
                    position: 'relative',
                    border: selectedImages.has(image.id) ? 2 : 0,
                    borderColor: 'primary.main',
                  }}
                >
                  <CardMedia
                    component="img"
                    height="120"
                    image={image.imageUrl}
                    alt={`图片 ${index + 1}`}
                    sx={{ cursor: 'pointer' }}
                    onClick={() => handleImageSelect(image.id)}
                  />
                  <CardActions sx={{ position: 'absolute', top: 0, right: 0, p: 0.5 }}>
                    <Checkbox
                      checked={selectedImages.has(image.id)}
                      onChange={() => handleImageSelect(image.id)}
                      sx={{ 
                        color: 'white',
                        bgcolor: 'rgba(0, 0, 0, 0.5)',
                        borderRadius: 1,
                        '&.Mui-checked': {
                          color: 'primary.main',
                          bgcolor: 'rgba(255, 255, 255, 0.9)',
                        }
                      }}
                    />
                  </CardActions>
                </Card>
              </Box>
            ))}
          </Box>
        </Box>
      )}

      {/* 新增图片 */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" gutterBottom>
          添加新图片
        </Typography>
        
        {newImagePreviews.length > 0 && (
          <Box sx={{ mb: 2 }}>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              待上传图片 ({newImages.length}张)
            </Typography>
                         <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
               {newImagePreviews.map((preview, index) => (
                 <Box key={index} sx={{ width: { xs: 'calc(50% - 8px)', sm: 'calc(33.33% - 11px)', md: 'calc(25% - 12px)' } }}>
                   <Card sx={{ position: 'relative' }}>
                     <CardMedia
                       component="img"
                       height="120"
                       image={preview}
                       alt={`新图片 ${index + 1}`}
                     />
                     <CardActions sx={{ position: 'absolute', top: 0, right: 0, p: 0.5 }}>
                       <IconButton
                         size="small"
                         onClick={() => handleRemoveNewImage(index)}
                         sx={{ 
                           color: 'white',
                           bgcolor: 'rgba(0, 0, 0, 0.5)',
                           '&:hover': {
                             bgcolor: 'rgba(255, 0, 0, 0.7)',
                           }
                         }}
                       >
                         <Delete fontSize="small" />
                       </IconButton>
                     </CardActions>
                   </Card>
                 </Box>
               ))}
             </Box>
          </Box>
        )}

        <MediaUploader
          accept="image/*"
          onUpload={handleAddImage}
          loading={loading}
          buttonText="添加图片"
          helperText="支持 JPG、PNG、GIF 格式，单张图片不超过10MB"
          maxSize={10}
        />
      </Box>

      {/* 操作按钮 */}
      {hasChanges && (
        <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end' }}>
          <Button
            variant="outlined"
            onClick={() => {
              setSelectedImages(new Set());
              setNewImages([]);
              setNewImagePreviews([]);
            }}
          >
            取消更改
          </Button>
          <Button
            variant="contained"
            onClick={handleSaveChanges}
            disabled={loading}
          >
            保存更改
          </Button>
        </Box>
      )}

      {!hasChanges && currentImages.length === 0 && (
        <Alert severity="info">
          暂无图片，请添加图片
        </Alert>
      )}

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除选中的 {selectedImages.size} 张图片吗？此操作不可撤销。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)}>
            取消
          </Button>
          <Button onClick={confirmDelete} color="error" autoFocus>
            确认删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}; 